﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using D2DEngine.Scene;
using Microsoft.Xna.Framework.Graphics;
using D2DEngine.Core;
using D2DEngine.Components;

namespace D2DEngine
{
    public class D2DMountComponent : D2DComponent
    {
        D2DSceneObject sceneObject;
        Dictionary<string, D2DMount> attachedObjects = new Dictionary<string, D2DMount>();

        /// <summary>
        /// The collection of objects mounted on this object
        /// </summary>
        public Dictionary<string, D2DMount> AttachedObjects
        {
            get { return this.attachedObjects; }
        }

        public override void OnRegister()
        {
            this.sceneObject = this.owner as D2DSceneObject;

            base.OnRegister();
        }

        /// <summary>
        /// Attach another to this object
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="name"></param>
        public void Attach(string name, D2DSceneObject obj, Vector2 mountPosition)
        {
            D2DMount mount = new D2DMount();
            
            mount.Position = mountPosition;
            mount.Rotation = this.sceneObject.Rotation;
            mount.SceneObject = obj;
            mount.SceneObject.Layer = this.sceneObject.Layer + 1;

            this.attachedObjects.Add(name, mount);
        }

        
        public D2DMountComponent()
        {           
        }


        /// <summary>
        /// Updates the mounted objects
        /// </summary>
        /// <param name="gameTime"></param>
        public override void Update(GameTime gameTime)
        {
            D2DMount mount; // Optimization
            foreach (string key in this.attachedObjects.Keys)
            {
                mount = this.attachedObjects[key];
                mount.SceneObject.Position = this.sceneObject.Position + mount.Position;
            }
        }

        

        /// <summary>
        /// Copies the component
        /// </summary>
        /// <param name="obj"></param>
        protected override void CopyTo(D2DComponent component)
        {
            base.CopyTo(component);

            D2DMountComponent comp = (D2DMountComponent)component;
            D2DMount clonedMount;

            foreach (string key in this.attachedObjects.Keys)
            {
                clonedMount = (D2DMount)this.attachedObjects[key].Clone();
                comp.attachedObjects.Add(key, clonedMount);
            }
        }
        
    }


}
